const app = getApp();
Page({
  data: {
    StatusBar: app.globalData.StatusBar,
    CustomBar: app.globalData.CustomBar,
    ColorList: app.globalData.ColorList,
    uname:'nothing',  //nothing是无缓存时的初始值  无缓存需要显示表单进行填写
    upwd:'nothing',
    token:null,   //登录状态
    info:null,    //用来判断授权与否
  },
  //wx.authorize({scope.userInfo success() {}})不能打开授权框，只能button opentype
  formSubmit: function (e) {//不填不能直接跳到不存在  填了要进入判断再授权
    let name=null;
    let pwd=null;
    console.log("submit", this.data.uname)
    //nothing是一开始就没有缓存，为了和页面显示区分开而定义的值。进入这个判断意味着''或者有缓存
    if (this.data.uname!=null && this.data.upwd!=null && this.data.uname != 'nothing' && this.data.upwd != 'nothing') {
      console.log("sign")
      if (this.data.uname == '' || this.data.upwd == '' || this.data.uname == null || this.data.upwd == null) {//''的时候表示需要填写表单(初始时本地无缓存)
        console.log("无缓存，需要填表单", this.data.uname)
        console.log("auth submit", e.detail.value)
        name = e.detail.value.inputUname;
        pwd = e.detail.value.inputPwd;
        /*this.data.uname = name;
        this.data.upwd = pwd;
        //不绑定视图，认证失败还是要显示表单
        console.log("表单信息赋给数据",this.data.uname,this.data.upwd)*/

        //表单信息未填写
        if (name == '' || pwd == '' || name == null || pwd == null) {
          wx.showToast({
            title: '请填写所有信息',
            icon: 'loading',
            duration: 1500
          });
        }
      }
      else{       //初始缓存存在
        name=this.data.uname;
        pwd=this.data.upwd;
        console.log("有缓存时",name,pwd)
        //this.setData({ token: 'success' })
      }
     // console.log('auth req suc', temp);  测试放这里
     /* console.log("auth submit name pwd", name, pwd)//认证通过注册成功，保存缓存
      wx.setStorageSync('name', name);
      wx.setStorageSync('pwd', pwd);
      this.setData({ uname: name, upwd: pwd });*/

      console.log("auth data", this.data.uname,name)
      let that = this;
//确保有信息 然后发起请求认证用户  存在才能授权发送openid
      if(!(name == '' || pwd == '' || name == null || pwd == null)&&this.data.token!='success')
      wx.request({
        header: {
          "Content-Type": "application/json"
        },
        url: 'http://10.10.11.195:8080/szgd/weChat/login?name=' + name + '&pass=' + pwd,// 登陆接口
        // data: { name: name, pass: pwd }, //nickName
        method: 'POST',
        success: function (res) {
          console.log('auth req res', res);
          var temp = res.data.resultMsg;  //因为用户超时之后每次都要验证，所以最好是传过来token，比较缓存        
          
          if (temp == "fail") {  //数据库没这用户
            console.log('auth req fail', temp, that.data.token);
            wx.showToast({  //Modal
              title: '用户不存在',
              icon: 'loading',
              duration: 1500
            })
          }
          else if(temp=='success'){    //身份认证通过
            console.log('auth req suc', temp);
            that.data.token = temp;
            that.setData({token:temp})
            console.log("auth submit name pwd", name, pwd, that.data.token)//认证通过注册成功，保存缓存
            wx.setStorageSync('name', name);
            wx.setStorageSync('pwd', pwd);
            that.setData({ uname: name, upwd: pwd }); //数据绑定，onpentype生效

            app.globalData.UserName = name  //用户名给全局变量
            console.log("auth put name into app", app.globalData.UserName)
            
            //回调查看授权结果
            if (app.globalData.userInfo && app.globalData.userInfo != '') {
              that.setData({ info: app.globalData.userInfo })
              console.log("auth info", that.data.info);
            }
            else
              app.userInfoReadyCallback = userInfo => {
                if (userInfo != '') {
                  this.setData({ info: userInfo })
                  console.log("callback info", that.data.info);
                }
              }
            //if没有授权
            if(!that.data.info)
              wx.showToast({
                title: '成功，请授权',
                icon: 'loading',
                duration: 1500
              })
            else {
              wx.showToast({
                title: '成功，待跳转',
                icon: 'loading',
                duration: 1500
              })
              that.myLogin();
            }
            //else 已有授权（当前环境为存在缓存）  mylogin
          }
        },
        fail: function (res) {
          console.log("auth validate fail", res);
          /*wx.redirectTo({
            url: '/pages/auth/auth'
          })*/
          wx.showToast({  //Modal
            title: '认证请求失败',
            icon: 'loading',
            duration: 1500
          })
        },
        complete:function(res){
          if (that.data.token == 'success') {
            console.log("认证成功，用户授权", that.data.token)
            //that.onGetUserInfo();
          }
        }
      });
    } 
    //这步做了之后再跳转
   // if (this.data.token=='success'||this.data.token==null)  //认证通过或者默认才能授权
    else if (this.data.uname == 'nothing' && this.data.upwd == 'nothing'){
      console.log("nothing ongetuser")
      this.onGetUserInfo();
    }
   /* else{
      //用户名密码有数据就放入本地缓存
     console.log("auth submit name pwd",name,pwd)
      wx.setStorageSync('name',name);
      wx.setStorageSync('pwd',pwd);
      this.setData({uname:name,upwd:pwd});
    
  }*/
  },

  onGetUserInfo: function (e) {   //授权时判断缓存
  console.log("auth userinfo e ",e)
    if ( this.data.uname == 'nothing' || this.data.upwd == 'nothing'){  //找不到缓存
      console.log("授权 name pwd  nothing",this.data.uname)
      this.setData({uname:'',upwd:''})
      wx.showToast({ 
        title: '请登录',
        icon: 'loading',
        duration: 1500
      })
    }
    else if(this.data.token=='success'){
      console.log("getinfo suc login")
      this.myLogin();  //注册授权成功发起登录请求
    }
    /*else if(e.detail)
     //填写信息再弹窗可能要页面判断  
      if (!this.logged && e.detail.userInfo) {        
        app.globalData.userInfo = e.detail.userInfo;
        console.log("auth user", e.detail.userInfo, e.detail);
        //this.validate();
      }*/
    
  },
  /*validate: function () {
    if (!app.globalData.userInfo.nickName)  //没授权
      wx.navigateTo({
        url: '/pages/auth/auth',
      });
    else{   
    var data = app.globalData.userInfo;
      console.log("auth glo user ", data);
    var nickName = app.globalData.userInfo.nickName;
    let uname=this.data.uname;
    let pwd = this.data.upwd;
    wx.request({
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      url: 'http://10.10.11.173:8989/user/ifUser',
      data: { name:uname,pass:pwd  }, //nickName
      method: 'POST',
      success: function (res) {
        console.log('auth req res', res);
        var temp = res.data.resultMsg;  //因为用户超时之后每次都要验证，所以最好是传过来token，比较缓存
        this.myLogin();  //注册授权成功发起登录请求
        if (temp == "fail") 
          console.log('auth req suc', temp);
        else {
          console.log('auth req suc', temp);
          wx.navigateTo({
            url: '/pages/index/index',
           })    
        }    
      },
      fail: function (res) {
        console.log("auth validate fail", res);
        wx.redirectTo({
          url: '/pages/auth/auth'
        })
        wx.showToast({  //Modal
          title: '登录失败',
          icon: 'loading',
          duration: 2000
        })
      },
    })
    }
  },*/
  myLogin:function(){  //换取唯一标识和用户信息，跳转首页
    let name=this.data.uname;
    let pwd=this.data.upwd;
    wx.login({
      success: res => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
        console.log("auth.js login", res)
        let code = res.code   //发给后台
//可能需要按照是否已经授权分别处理  授权了就用openid，否则code
        wx.request({ 
          url: 'http://10.10.11.195:8080/szgd/weChat/getOpenId?name='+name+"&pass="+pwd+"&code="+code, //获取openID和用户对象
          //data: { name: name, pass: pwd, code: code },
          header: {
            'content-type': 'application/json'
          },
          success: function (res) {  //返回user对象
            console.log("auth send code ", res)
            let userName=res.data.name;
            let userWork=res.data.workType;
            let userId = res.data.id;
            let openid=res.data.openId;
            app.globalData.userName=userName;
            app.globalData.userWork = userWork;
            app.globalData.userId = userId;
            app.globalData.openid = openid;
            wx.setStorageSync('open', openid);
            console.log("auth get from code", app.globalData.userName, app.globalData.userWork, app.globalData.openid);
            wx.showToast({
              title: '授权成功',
              icon: 'success',
              duration: 1500
            })
            wx.navigateTo({
              url: '/pages/index/index',
            })
          },
          fail:function(res){
            console.log("auth send code fail", res)
            wx.showToast({
              title: '登录请求失败',
              icon: 'loading',
              duration: 1500
            })
          }
        })       
      }
    })
  },
  onLoad: function (options) { 
    let name=null;
    let pwd=null;
    name=wx.getStorageSync('name')
    pwd=wx.getStorageSync('pwd')
    if(name!=''&&pwd!='')
      this.setData({ uname: name, upwd: pwd });
    else this.setData({ uname: 'nothing', upwd: 'nothing' });
    console.log("auth onload get from storage", name, pwd,this.data.uname,this.data.upwd)
  }
});
